package cn.steel.controller.supplier;

import cn.hutool.core.bean.BeanUtil;
import cn.steel.domain.dto.SupplierInfoDto;
import cn.steel.domain.entity.SupplierInfo;
import cn.steel.domain.entity.User;
import cn.steel.domain.vo.SupplierInfoVo;
import cn.steel.service.SupplierInfoService;
import cn.steel.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;

@Slf4j
@Controller
@RequestMapping("/supplier/profile")
@Api(tags = "供应商店铺信息管理")
@PreAuthorize("hasAuthority('SUPPLIER')")
@RequiredArgsConstructor
public class SupplierProfileController {

    private final SupplierInfoService supplierInfoService;
    private final UserService userService;

    @ApiOperation("显示供应商店铺信息编辑页面")
    @GetMapping
    public String editProfileForm(
            @SessionAttribute(value = "user", required = false) User user,
            Model model) {
        log.info("显示供应商店铺信息编辑页面");
        Long supplierId = user.getId(); // 从登录用户获取 ID
        User fetchedUser = userService.getUserById(supplierId);
        SupplierInfo supplierInfo = supplierInfoService.getSupplierInfoByUserId(supplierId);
        SupplierInfoVo supplierInfoVo = new SupplierInfoVo();
        BeanUtil.copyProperties(user, supplierInfoVo);
        BeanUtil.copyProperties(supplierInfo, supplierInfoVo);
        model.addAttribute("user", supplierInfoVo);
        return "supplier/profile_form";
    }

    @ApiOperation("修改供应商店铺信息")
    @PostMapping("/update")
    public String updateProfile(
            @SessionAttribute(value = "user", required = false) User user,
            @Valid @ModelAttribute SupplierInfoDto supplierInfoDto,
            BindingResult result,
            @RequestParam(value = "logoFile", required = false) MultipartFile logoFile,
            @RequestParam(value = "licenseFile", required = false) MultipartFile licenseFile,
            Model model) {
        log.info("修改供应商店铺信息: userSupplierDto={}", supplierInfoDto);
        Long supplierId = user.getId(); // 从登录用户获取 ID        if (result.hasErrors()) {
        if (result.hasErrors()) {
            SupplierInfoVo supplierInfoVo = BeanUtil.toBean(supplierInfoDto, SupplierInfoVo.class);
            supplierInfoVo.setUserId(supplierId);
            model.addAttribute("user", supplierInfoVo);
            return "supplier/profile_form";
        }

        SupplierInfo supplierInfo = BeanUtil.toBean(supplierInfoDto, SupplierInfo.class);
        supplierInfo.setUserId(supplierId);
        supplierInfoService.updateSupplierInfo(supplierInfo,logoFile,licenseFile);
        return"redirect:/supplier/profile?success=true";
    }

    @ApiOperation("显示修改密码页面")
    @GetMapping("/change_password")
    public String showChangePasswordForm(@SessionAttribute(value = "user", required = false) User user, Model model) {
        if (user == null ||  !user.getRole().equals("SUPPLIER")){
            log.warn("用户未登录，跳转到登录页面");
            return "redirect:/login";
        }
        log.info("显示修改密码页面,userId={}", user.getId());
        model.addAttribute("userId", user.getId());
        return "supplier/change_password";
    }

    @ApiOperation("修改密码")
    @PostMapping("/change_password")
    public String changePassword(
            @SessionAttribute(value = "user", required = false) User user,
            @RequestParam("oldPassword") String oldPassword,
            @RequestParam("newPassword") String newPassword,
            @RequestParam("confirmPassword") String confirmPassword,
            Model model) {
        if (user == null ||  !user.getRole().equals("SUPPLIER")){
            log.warn("用户未登录，跳转到登录页面");
            return "redirect:/login";
        }
        log.info("修改密码: userId={}", user.getId());
        if (!newPassword.equals(confirmPassword)){
            model.addAttribute("error", "新密码和确认密码不一致");
            model.addAttribute("userId", user.getId());
            return "supplier/change_password";
        }
        try {
            userService.changePassword(user.getId(), oldPassword, newPassword);
            model.addAttribute("success", "密码修改成功");
            log.info("用户密码修改成功: userId={}", user.getId());
//            return "redirect:/supplier/profile?success=true";
        }catch (IllegalArgumentException e){
            log.error("密码修改失败: userId={}, error={}", user.getId(), e.getMessage());
            model.addAttribute("error", e.getMessage());
            model.addAttribute("userId", user.getId());
            return "supplier/change_password";
        }catch (Exception e) {
            // 捕获其他未预期的异常
            log.error("系统异常: userId={}, 错误信息={}", user.getId(), e.getMessage());
            model.addAttribute("error", "系统错误，请稍后再试");
            model.addAttribute("userId", user.getId());
            return "supplier/change_password";
        }
        return "supplier/change_password";
        }
    }
